import fetchInstance from './request/axios'
import { BASE_URL, BASE_URL1, TIME_OUT } from './request/config'
import cache from '@/utils/cache'
import message from '@/utils/message'

// 可以new多个fetchInstance 防止项目多个接口地址
const fetch = new fetchInstance({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      const token = cache.getCache('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      if (res.data.code == 401) {
        cache.clearCache()
        throw new Error()
      }
      if (res.data.code == 500) {
        message.error("500接口报错")
        throw new Error()
      }
      return res.data
    },
    responseInterceptorCatch(err) {
      return err
    }
  }
})

const fetch1 = new fetchInstance({
  baseURL: BASE_URL1,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config) => {
      // const token = cache.getCache('token')
      // if (token) {
      //   config.headers.Authorization = `Bearer ${token}`
      // }
      // return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res
    },
    responseInterceptorCatch(err) {
      return err
    }
  }
})

export {
  fetch,
  fetch1
}
